from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import Inventory, Product, Category, Supplier, db
from utils import error, success
from datetime import datetime

inventory_api = Blueprint('inventory_api', __name__, url_prefix='/api/inventory')

@inventory_api.route('/', methods=['GET'])
@jwt_required()
def get_inventory():
    """获取库存列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('page_size', 10, type=int)
        search = request.args.get('search', '')
        category_id = request.args.get('category_id', type=int)
        category_name = request.args.get('category_name', '')
        supplier_id = request.args.get('supplier_id', type=int)
        supplier_name = request.args.get('supplier_name', '')
        low_stock = request.args.get('low_stock', '').lower() == 'true'
        
        # 使用简单的查询，避免复杂的关联
        query = db.session.query(Inventory, Product).join(Product)
        
        # 搜索过滤
        if search:
            query = query.filter(
                Product.name.contains(search) 
            )
        
        # 分类过滤 - 支持按分类名称搜索
        if category_id:
            query = query.filter(Product.category_id == category_id)
        elif category_name:
            # 根据分类名称搜索
            query = query.join(Category, Product.category_id == Category.id).filter(Category.name.contains(category_name))
        
        # 供应商过滤
        if supplier_id:
            query = query.filter(Product.supplier_id == supplier_id)
        elif supplier_name:
            # 根据供应商名称搜索
            query = query.join(Supplier, Product.supplier_id == Supplier.id).filter(Supplier.name.contains(supplier_name))
        
        # 低库存过滤
        if low_stock:
            query = query.filter(Inventory.current_stock <= Product.min_stock)
        
        # 分页
        print(f"查询参数: page={page}, per_page={per_page}, search={search}, low_stock={low_stock}")
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        print(f"查询结果数量: {pagination.total}")
        
        inventory_list = []
        for inventory, product in pagination.items:
            # 获取供应商和分类信息
            supplier_name = '未设置'
            category_name = '未设置'
            
            if product.supplier:
                supplier_name = product.supplier.name
            if product.category:
                category_name = product.category.name
            
            inventory_list.append({
                'id': inventory.id,
                'product_id': product.id,
                'product_name': product.name,
                'product_sku': product.sku,
                'category_name': category_name,
                'supplier_name': supplier_name,
                'unit': product.unit,
                'unit_price': product.unit_price,
                'cost_price': product.cost_price,
                'min_stock': product.min_stock,
                'max_stock': product.max_stock,
                'current_stock': inventory.current_stock,
                'reserved_stock': inventory.reserved_stock,
                'available_stock': inventory.available_stock,
                'stock_value': inventory.current_stock * product.cost_price,
                'is_low_stock': inventory.current_stock <= product.min_stock,
                'last_updated': inventory.last_updated.isoformat(),
                'created_at': inventory.created_at.isoformat()
            })
        
        return success(data={
            'inventory': inventory_list,
            'total': pagination.total,
            'pagination': {
                'page': pagination.page,
                'page_size': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        print(f"库存API错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return error(500, f'Failed to get inventory list: {str(e)}').to_response()



@inventory_api.route('/statistics', methods=['GET'])
@jwt_required()
def get_inventory_statistics():
    """获取库存统计信息"""
    try:
        # 总商品数
        total_products = Product.query.filter_by(status='active').count()
        
        # 总库存价值
        total_value = db.session.query(
            db.func.sum(Inventory.current_stock * Product.cost_price)
        ).join(Product).filter(Product.status == 'active').scalar() or 0
        
        # 低库存商品数
        low_stock_count = db.session.query(Inventory).join(Product).filter(
            Inventory.current_stock <= Product.min_stock,
            Product.status == 'active'
        ).count()
        
        # 零库存商品数
        zero_stock_count = db.session.query(Inventory).join(Product).filter(
            Inventory.current_stock == 0,
            Product.status == 'active'
        ).count()
        
        # 按分类统计
        category_stats = db.session.query(
            Category.name,
            db.func.count(Product.id),
            db.func.sum(Inventory.current_stock * Product.cost_price)
        ).select_from(Category).join(Product, Category.id == Product.category_id).join(Inventory, Product.id == Inventory.product_id).filter(
            Product.status == 'active'
        ).group_by(Category.id, Category.name).all()
        
        category_data = []
        for name, count, value in category_stats:
            category_data.append({
                'category_name': name,
                'product_count': count,
                'total_value': float(value or 0)
            })
        
        return jsonify({
            'success': True,
            'data': {
                'total_products': total_products,
                'total_value': float(total_value),
                'low_stock_count': low_stock_count,
                'zero_stock_count': zero_stock_count,
                'category_stats': category_data
            }
        })
        
    except Exception as e:
        return error(500, f'Failed to get inventory statistics: {str(e)}').to_response()

@inventory_api.route('/low-stock', methods=['GET'])
@jwt_required()
def get_low_stock_products():
    """获取低库存商品列表"""
    try:
        low_stock_products = db.session.query(Inventory, Product).join(Product).filter(
            Inventory.current_stock <= Product.min_stock,
            Product.status == 'active'
        ).all()
        
        products = []
        for inventory, product in low_stock_products:
            products.append({
                'id': product.id,
                'name': product.name,
                'sku': product.sku,
                'unit': product.unit,
                'min_stock': product.min_stock,
                'current_stock': inventory.current_stock,
                'shortage': product.min_stock - inventory.current_stock,
                'unit_price': product.unit_price,
                'cost_price': product.cost_price
            })
        
        return jsonify({
            'success': True,
            'data': products
        })
        
    except Exception as e:
        return error(500, f'Failed to get low stock products: {str(e)}').to_response()
